<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd()">+新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="查询用户">
        <el-input v-model="formInline.keyword" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSerch">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="UserData" style="width: 100%; height: 500px">
      <el-table-column
        fixed
        v-for="(item, index) in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 125"
      />

      <el-table-column fixed="right" label="操作" min-width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleClick(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="config.total"
      :page-size="config.pageSize"
      @current-change="changePage"
      class="pager"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action === 'add' ? '新增用户' : '编辑用户'"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      label-position="top"
      label-width="100px"
      :model="formLabelAlign"
      style="max-width: 460px"
      size="default"
      ref="userForm"
    >
      <el-row justify="space-between">
        <el-col :span="10">
          <el-form-item
            label="用户名"
            prop="userName"
            :rules="[{ required: true, message: '用户名是必填项' }]"
          >
            <el-input v-model="formLabelAlign.userName" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="密码"
            prop="userPassword"
            :rules="[
              { required: true, message: '密码是必填项' },
            ]"
          >
            <el-input
              v-model.number="formLabelAlign.userPassword"
              placeholder="请输入密码"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row justify="space-between">
        <el-col :span="10">
          <el-form-item
            label="邮箱"
            prop="email"
            :rules="[{ required: true, message: '邮箱是必填项' }]"
          >
            <el-input
              v-model.trim="formLabelAlign.email"
              placeholder="请输入邮箱"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="用户权限"
            prop="roleId"
            :rules="[{ required: true, message: '用户权限是必填项' }]"
          >
          <el-select v-model="formLabelAlign.roleId" placeholder="请选择" size="large">
            <el-option
              v-for="item in rule"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row justify="end">
        <el-button @click="handleCancel()">取消</el-button>
        <el-button
          type="primary"
          @click="
            onSubmit() //提交表单
          "
        >
          确定
        </el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
const rule = ref([
  {
    value:0,
    label:'管理员'
  },
  {
    value:1,
    label:'普通用户'
  }
])
const UserData = ref([]);
//表单数据名
const tableLabel = ref([
  {
    prop: "userId",
    label: "用户id",
  },
  {
    prop: "userName",
    label: "用户名",
  },
  {
    prop: "phone",
    label: "手机号",
    width: 200,
  },
  {
    prop: "email",
    label: "邮箱",
    width: 320,
  },
  {
    prop: "createdAt",
    label: "用户创建时间",
    width: 320,
  },
]);
//获取当前实例
const { proxy } = getCurrentInstance();
//分页器配置
const config = reactive({
  total: 0,
  page: 0,
  pageNum: 20,
  userName: "",
});
//获取用户数据
const getUserData = async (config) => {
  let res = await proxy.$api.getUser(config);
  console.log(res)
  UserData.value = res.data.map((item) => {
    return item;
  });
  config.total = res.count;
};
//搜索用户数据
const searchUserData = async (config) => {
  let res = await proxy.$api.searchUser(config);
  console.log(res)
  UserData.value = res.data.map((item) => {
    return item;
  });
  config.total = res.count;
};
//当页面加载时获取数据
onMounted(() => {
  getUserData(config);
});
//监听分页器的变化
const changePage = (page) => {
  console.log(page);
  config.page = page;
  getUserData(config);
};
//搜索框
const formInline = reactive({
  keyword: "",
});
const handleSerch = () => {
  console.log(formInline.keyword);
  // 处理搜索操作
  config.userName = formInline.keyword;
  searchUserData(config);
};
//控制新增弹窗的显示
const dialogVisible = ref(false);
const handleClose = (done) => {
  ElMessageBox.confirm("确定关闭吗")
    .then(() => {
      proxy.$refs.userForm.resetFields();
      done();
    })
    .catch(() => {
      // catch error
    });
};
//添加用户的form数据
const formLabelAlign = reactive({
  userName: "", //用户名
  userPassword: "", //密码
  email: "", //邮箱
  roleId: "", //权限
  
});
//添加用户方法
const addUsers = async (user) => {
  console.log(user)
  let x = await proxy.$api.addUser(user);
  console.log(x)
  //判断返回值是否正确
  if (x.code == 200) {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
  }
  //清空表单数据
  proxy.$refs.userForm.resetFields();
  //重新获取数据
  getUserData(config);
};
//编辑用户方法
const editUsers = async (user) => {
  let x = await proxy.$api.editUser(user);
  //判断返回值是否正确
  console.log(x);
  if (x.code == 20000) {
    ElMessage({
      message: x.data.message,
      type: "success",
    });
  }
  //清空表单数据
  proxy.$refs.userForm.resetFields();
  //重新获取数据
  getUserData(config);
};
//添加/编辑用户
const onSubmit = () => {
  //首先判断表单是否填写完整
  proxy.$refs.userForm.validate((valid) => {
    if (valid) {
      // 判断是添加用户还是编辑用户
      if (action.value == "add") {
        //添加用户
        addUsers(formLabelAlign);
      } else {
        //编辑用户
        editUsers(formLabelAlign);
      }
      //关闭弹窗
      dialogVisible.value = false;
    } else {
      ElMessage.error("请正确填写内容");
    }
  });
};
//取消添加/编辑用户
const handleCancel = () => {
  dialogVisible.value = false; //关闭弹窗
  proxy.$refs.userForm.resetFields(); //当点击取消按钮时，重置表单
};
//用于区分是添加用户还是编辑用户
const action = ref("add");
//新增用户
const handleAdd = () => {
  //修改action的值为add
  action.value = "add";
  //打开弹窗
  dialogVisible.value = true;
};
//编辑用户
const handleClick = (row) => {
  console.log(row);
  // 处理编辑操作
  action.value = "edit"; //修改action的值为edit
  dialogVisible.value = true; //打开弹窗
  //将数据赋值给表单 浅拷贝
  proxy.$nextTick(() => {
    Object.assign(formLabelAlign, row);
  });
};
//删除用户
const handleDelete = (row) => {
  console.log(row);
  // 处理删除操作
  ElMessageBox.confirm("确定删除吗")
    .then(async () => {
      let x = await proxy.$api.deleteUser(row.userId);
      console.log(x)
      //判断返回值是否正确
      if (x.code == 200) {
        ElMessage({
          message: x.message,
          type: "success",
        });
      }
      //重新获取数据
      getUserData(config);
    })
    .catch(() => {
      // catch error
    });
};
</script>

<style lang="less" scoped>
.table {
  position: relative;
  width: 100%;
  .pager {
    position: absolute;
    margin-top: 2vh;
    left: 60%;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
